<?php


namespace app\admin\controller;


use app\common\model\AdPlayHistory;
use think\Controller;
use think\Db;
use think\facade\Request;

class Ecpm extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkAdminToken::class'
    ];

    //ecpm的列表
    public function index()
    {
//        $admin_id=Request::param('admin_id');
        $page = Request::param('page', 1);
        $mini_app_code = Request::param('mini_app_code', 'test');       //App的code
        $pageSize = Request::param('pageSize', 20);           //哪一天的数据

        //获取列表
        $list = Db::table('ecpm')->where('mini_app_code',$mini_app_code)->order('id','desc')->withAttr('add_time', function ($value, $data) {
            return date("Y-m-d H:i:s", $value);
        })->page($page, $pageSize)->select();

        $count = Db::table('ecpm')->where('mini_app_code',$mini_app_code)->count('id');

        $data = [
            'list' => $list,
            'page_num' => ceil($count / $pageSize),
            'page' => $page
        ];

        $this->result($data, 200);
    }

    //添加ecpm，并且计算收益
    public function add()
    {

        $ecpm = Request::param('ecpm', 0);
        $mini_app_code = Request::param('mini_app_code', 'test');       //App的code

        if ($ecpm == 0) {
            $this->result('', 400, 'ecpm错误');
        }

        //删掉今天设置的ecpm，保证使用的是最新的ecpm计算
        //今天更新过ecpm，删掉重复的
        $res2 = Db::name('ecpm')->where([
            ['add_time', 'BETWEEN', today()],
            ['mini_app_code', '=', $mini_app_code]
        ])->delete();

        //计算ecpm
        $res = \app\common\model\Ecpm::create([
            'yesterday_ecpm' => $ecpm,
            'mini_app_code'=>$mini_app_code,
            'add_time' => time()
        ]);

        //计算收益
        $this->calcIncome($ecpm,$mini_app_code);
        $this->result('', 200,'更新成功');
    }

    //计算每天的收益(ecpm值，，流量主的问题)
    public function calcIncome($ecpm,  $mini_app_code)
    {
        //昨天的开始时间戳和结束时间戳
        $yesterday = yesterday();

        $yesterday_ecpm = \app\common\model\Ecpm::yesterdayEcpm($mini_app_code);

        $mini_app=\app\common\model\MiniApp::where('code',$mini_app_code)->find();

        //判断程序是否存在
        if(!$mini_app_code)$this->result($mini_app,400,'程序不存在');

        //获取昨天的所有播放记录
        $ad_play_history = AdPlayHistory::alias('ad')->where([
            ['ad.add_time', 'BETWEEN', $yesterday],
            ['ad.mini_app_code', '=', $mini_app_code]
        ])
            ->join('user user','ad.promote_user_id=user.id')
            ->field('promote_user_id,count(promote_user_id) as play_count,user.vip,user.lv_1_id,user.lv_2_id')
            ->group('promote_user_id')
            ->select();
//        $this->result($ad_play_history,400,'程序不存在');

        //计算每个用户的激励视频收益，并且插入数据库
        $user_income = [];

        foreach ($ad_play_history as $key => $value) {

            //扣除前的总收益为 ecpm/1000 * 完整播放次数   结果四舍五入，保留两位小数
            $money = round($yesterday_ecpm / 1000 * $value['play_count'], 2);

            //流量主提成
            if($value['vip']){
                $pro=$mini_app->vip_rate;
            }else{
                $pro=$mini_app->user_rate;
            }

            //金额不足以分给上级和上上级的时候，直接全部加在自己的账户里面
            if($money>0.01 && $money<0.34){
                //所有用户的收益记录
                array_push($user_income, [
                    'user_id' => $value['promote_user_id'],
                    'lv_1_id'=>$value['lv_1_id'],
                    'lv_2_id'=>$value['lv_2_id'],
                    'money' =>$money,
                    'lv_1_income'=>0,
                    'lv_2_income'=>0,
                    'views' => $value['play_count'],
                    'mini_app_code' => $mini_app_code,
                    'ecpm' => $yesterday_ecpm,
                    'add_time' => time()
                ]);
            }else if($money>=0.34){
                //金额足够分的时候，分给上级和上上级

                //所有用户的激励视频收益记录
                array_push($user_income, [
                    'user_id' => $value['promote_user_id'],
                    'lv_1_id'=>$value['lv_1_id'],
                    'lv_2_id'=>$value['lv_2_id'],
                    'money' =>round( $money*$pro,2),
                    'lv_1_income'=>round($money* $mini_app->lv_1_rate,2),
                    'lv_2_income'=>round( $money*$mini_app->lv_2_rate,2),
                    'views' => $value['play_count'],
                    'mini_app_code' => $mini_app_code,
                    'ecpm' => $yesterday_ecpm,
                    'add_time' => time()
                ]);

                //对流量主的金额进行更新
                Db::table('user')
                    ->where('id', $value['promote_user_id'])
                    ->inc('money', round( $money*$pro,2))
                    ->inc('lv_1_income', round($money*$mini_app->lv_1_rate,2))
                    ->inc('lv_2_income', round($money*$mini_app->lv_2_rate,2))->update();

                //上级不为0的时候，才有上上级
                if($value['lv_1_id']){
                    //给流量主上级加钱
                    Db::table('user')
                        ->where('id', $value['lv_1_id'])
                        ->setInc('money', round($money*$mini_app->lv_1_rate,2)) ;

                    if($value['lv_2_id']){
                        //给流量主上上级加钱
                        Db::table('user')
                            ->where('id', $value['lv_2_id'])
                            ->setInc('money', round($money*$mini_app->lv_2_rate,2)) ;
                    }
                }
            }else{

                //总共的金额不足一分钱，不做任何处理
            }
        }

        //为了防止重复计算，对昨天的进行删除操作，再插入
        $res2 = Db::name('user_income')->where([
            ['add_time', 'BETWEEN', today()],
            ['mini_app_code', '=', $mini_app_code]
        ])->delete();

        //流量主收益插入数据库
        $res = Db::name('user_income')->data($user_income)->insertAll();

    }

}
